import publics from './public.js'
import Vue from 'vue'
import Vuex from 'vuex'
var token;
Vue.use(Vuex)
const ajax = (opt) => {
	if (uni.getStorageSync('token_token')) {
		// opt.data.Authorization = uni.getStorageSync('token_token');
	} else {
		// opt.data.Authorization = '';
	}
	fangfa(opt)

	function fangfa(opt) {
		// console.log('denglu')
		// login.commit("show_login")
		opt = opt || {};
		opt.url = opt.url || '';
		opt.data = opt.data || null;
		opt.method = opt.method || 'POST';
		opt.header = opt.header || {
			'Content-Type' : 'application/json',
			'Authorization': uni.getStorageSync('token_token')
		};
		opt.success = opt.success || function() {};
		if (opt.tishi == 1) {
			//显示正在加载
			store.commit("request_show_loading")
		} else if (opt.tishi == 2) {
			uni.stopPullDownRefresh(); //停止下拉刷新动画
		}
		if(opt.zhuang==1){
			opt.method=opt.method;
		}else{
			opt.method='POST'
		}
		// opt.method
		uni.request({
			url: publics.hosturl + opt.url,
			data: opt.data,
			method:opt.method,
			header: opt.header,
			dataType: 'json',
			timeout: 40000,
			success: (res) => {
				if(opt.zhuang==1){
					opt.success(res.data);
				}else{
					if (res.data.code != 1) {
						if (res.data.code == 500 || res.data.code == 401) {
							uni.redirectTo({
								url: '/view/public/login'
							})
							return false;
						}
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						});
					} else {
						opt.success(res.data);
					}
					
				}
			},
			fail: (err) =>  {
				console.log(err)
				console.log('fail')
			},
			
			complete: (err) => {
				if (opt.tishi == 1) {
					
					store.commit("request_hide_loading")
				} else if (opt.tishi == 2) {
					uni.showToast({
						title: '刷新成功',
						icon: "none"
					});
					uni.stopPullDownRefresh(); //停止下拉刷新动画
				} else if (opt.tishi == '11111') {
					opt.success(err);
					return false
				}
			},
		})
	}

}

const store = new Vuex.Store({
	state: {
		requestLoading: false //加载等待是否显示
	},
	mutations: {
		//显示请求加载动画
		request_show_loading(state) {
			state.requestLoading = true;
		},
		//隐藏请求加载动画
		request_hide_loading(state) {
			state.requestLoading = false;
		}
	}
})


export default {
	ajax, //数据请求
	store //加载
}
